package com.wenjie.terminal.util;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;

import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    private final Context context;
    private final File folder;

    public FileUtil(Context context) {
        this.context = context;

        // 获取文件夹路径
        File documentsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
        this.folder = new File(documentsDir, "wenjie");
        // 确保文件夹存在
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    /**
     * 检查并请求文件读写权限（适用于 Android 6.0 及以上）
     */
    private boolean isNotPermissions() {
        int writePermission = ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int readPermission = ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE);
        return writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 保存文件
     *
     * @param fileName 文件名
     * @param content  文件内容（字节数组）
     */
    public void addFile(String fileName, byte[] content) {
        if (isNotPermissions()) {
            CLog.e("无文件操作权限");
            return;
        }

        File file = new File(folder, fileName);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 移动文件
     */
    public void moveFile(String filePath) {
        File sourceFile = new File(filePath);
        String fileName = sourceFile.getName();
        File targetFile = new File(folder, fileName);

        // 执行文件移动操作
        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(targetFile)) {

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }

            // 关闭流后删除源文件
            sourceFile.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 清空文件夹下所有文件
     */
    public void clearFolder() {
        if (isNotPermissions()) {
            CLog.e("无文件操作权限");
            return;
        }

        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    file.delete();
                }
            }
        }
    }

    /**
     * 获取文件夹下所有文件
     */
    public List<File> getAllFile() {
        if (isNotPermissions()) {
            CLog.e("无文件操作权限");
            return new ArrayList<>();
        }

        File[] files = folder.listFiles();
        if (files == null) {
            return new ArrayList<>();
        }

        List<File> fileList = new ArrayList<>();
        for (File file : files) {
            if (file.isFile()) {
                fileList.add(file);
            }
        }

        return fileList;
    }
}